package api_auth

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"wrblog-api-go/app/common/constants"
	"wrblog-api-go/app/common/token"
	"wrblog-api-go/app/service"
	"wrblog-api-go/app/service/service_sys"
	"wrblog-api-go/pkg/mylog"
	"wrblog-api-go/pkg/redis"
	"wrblog-api-go/pkg/request"
	"wrblog-api-go/pkg/result"
	"wrblog-api-go/pkg/utils"
)

// @Tags  Auth - 认证授权
// @Summary  登录接口（加密）
// @Accept json
// @Produce json
// @Param loginForm body token.LoginForm true "loginForm"
// @Success 200 {object} result.Result "OK"
// @Router /auth/loginKey [post]
func ApiLoginKey(c *gin.Context) {
	raw, _ := c.Get(request.BindObj)
	loginForm := raw.(token.LoginForm)
	client, _ := c.Get("clientInfo")
	clientInfo := client.(token.ClientInfo)
	tokenInfo, err := service.LoginKey(loginForm, clientInfo)
	if err != nil {
		go service_sys.AddLoginiforOk(clientInfo, loginForm.Ak, fmt.Sprintf("登录失败，%s", err))
		result.Fail(err).Json(c)
	} else {
		go service_sys.AddLoginiforErr(clientInfo, loginForm.Ak, "登录成功！")
		result.Ok(tokenInfo).Json(c)
	}
}

// @Tags  Auth - 认证授权
// @Summary  退出登录
// @Accept json
// @Produce json
// @Param Authorization header string true "Authorization"
// @Success 200 {object} result.Result "OK"
// @Router /auth/logout [get]
func ApiLogout(c *gin.Context) {
	loginUser := token.GetLoginUser(c)
	if !utils.IsEmpty(loginUser) {
		if token.IsAdmin(loginUser.UserId) {
			redis.Del(fmt.Sprintf("%s%d:*", constants.LOGIN_USER_KEY, loginUser.UserId))
		} else {
			redis.Del(fmt.Sprintf("%s%d:%s", constants.LOGIN_USER_KEY, loginUser.UserId, loginUser.UserKey))
		}
		mylog.MyLog.Debugf("用户退出登录：%d:%s", loginUser.UserId, loginUser.UserKey)
	}
	result.Ok(nil).Json(c)
}
